package routers

import (
	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/net/ghttp"
	"net/http"
	"seawolf-admin-go/utility/response"
)

// DefaultHandlerResponse 本中间件为了统一处理返回值
type DefaultHandlerResponse struct {
	Code     int         `json:"code"    dc:"Error code"`
	Message  string      `json:"message" dc:"Error message"`
	Data     interface{} `json:"data"    dc:"Result data for certain request according API definition"`
	Version  string      `json:"version" dc:"API version"`
	DateTime string      `json:"datetime" dc:"request datetime"`
}

// MiddlewareHandlerResponse is the default middleware handling handler response object and its error.
func MiddlewareHandlerResponse(r *ghttp.Request) {
	r.Middleware.Next()

	// There's custom buffer content, it then exits current handler.
	if r.Response.BufferLength() > 0 {
		return
	}

	var (
		msg  string
		err  = r.GetError()
		res  = r.GetHandlerResponse()
		code = gerror.Code(err)
	)
	// 统一处理错误
	if err != nil {
		if code == gcode.CodeNil {
			code = gcode.CodeInternalError
		}
		msg = err.Error()
	} else if r.Response.Status > 0 && r.Response.Status != http.StatusOK {
		msg = http.StatusText(r.Response.Status)
		switch r.Response.Status {
		case http.StatusNotFound:
			code = gcode.CodeNotFound
		case http.StatusForbidden:
			code = gcode.CodeNotAuthorized
		default:
			code = gcode.CodeUnknown
		}
	} else {
		code = gcode.CodeOK
	}
	response.JsonExit(r, code.Code(), msg, res)
}
